<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .test_checks {
        width: 400px;
        height: 200px;

        padding: 10px;
        margin: 10px auto;
        text-align: center;
        line-height: 30px;
        font-size: 14px;
        color: #000;
        background-color: #fff;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
        position: relative;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    <div class="test_checks">
      <h2>JavaScript原生全选、反选功能</h2>
      <input type="checkbox" id="selectAll" /> 全选
      <br />
      <br />
      <input type="checkbox" class="checkbox" /> Item 1
      <br />
      <input type="checkbox" class="checkbox" /> Item 2
      <br />
      <input type="checkbox" class="checkbox" /> Item 3
      <br />
    </div>

    <script>
      let All = document.querySelector("#selectAll");
      let inputs = document.querySelectorAll(".checkbox");
      All.onclick = function () {
        for (let i = 0; i < inputs.length; i++) {
          inputs[i].checked = this.checked;
        }
      };
      for (let i = 0; i < inputs.length; i++) {
        inputs[i].onclick = function () {
          let flag = true;
          for (let j = 0; j < inputs.length; j++) {
            if (inputs[j].checked === false) {
              flag = false;
              break;
            }
          }
          if (flag) {
            console.log("全部选中了");
            All.checked = true;
          } else {
            console.log("没有全部选中");
            All.checked = false;
          }
          // All.checked = flag;
        };
      }
    </script>
  </body>
</html>
